import tensorflow as tf
import numpy as np
# 本节重点：滑动平均 moving average 相当于低通滤波

w1 = tf.Variable( 0, dtype=tf.float32)

# 反向传播方法
# 训练轮数参数，标注为不可训练
global_step = tf.Variable(0,trainable = False)
MOVING_AVERAGE_DECAY = 0.99
# 实例化滑动平均
ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step)
# 更新列表 trainable_variables自动将所有带训练数据汇总为列表
ema_op = ema.apply(tf.trainable_variables())

# 查看影子值
with tf.Session() as sess:
    init_op = tf.global_variables_initializer() # 全局初始化参数，初始化节点
    sess.run(init_op)
    print ( sess.run ([w1, ema.average(w1)]) )

    # 参数w1赋值为1
    sess.run(tf.assign(w1,1))
    sess.run(ema_op)
    print ( sess.run([w1, ema.average(w1)]) )

    # 更新step和w1，模拟出100轮后，参数w1变为10
    sess.run(tf.assign(global_step,100))
    sess.run(tf.assign(w1,10))
    sess.run(ema_op)
    print ( sess.run([w1, ema.average(w1)]) )

    # 每次sess.run会更新一次w1的滑动平均值
    sess.run(ema_op)
    print ( sess.run([w1, ema.average(w1)]) )

    sess.run(ema_op)
    print ( sess.run([w1, ema.average(w1)]) )

    sess.run(ema_op)
    print ( sess.run([w1, ema.average(w1)]) )

    sess.run(ema_op)
    print ( sess.run([w1, ema.average(w1)]) )